package com.learn.sunday.stock.common;

import com.learn.sunday.stock.bean.LockWork;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

@Slf4j
public class DistributedLocker {

    public final static String LOCK_PREFIX = "lock-";

    public final static Long LOCKER_WAITE_TIME = 10L;

    public final static Long LOCKER_LOCK_TIME = 100L;

    @Autowired
    private RedissonClient redissonClient;



    public void tryLock(final LockWork lockWork) {


        RLock lock = null;
        try {
            log.info("start get lock.......");
            lock = redissonClient.getFairLock(LOCK_PREFIX + lockWork.getName());
//            log.info("create lock key:{},try get lock", LOCK_PREFIX + lockWork.getName());
            while (!lock.tryLock(LOCKER_WAITE_TIME, LOCKER_LOCK_TIME, TimeUnit.MICROSECONDS)){
                log.info("wait to get dis lock");
                Thread.sleep(1L);
            }
            log.info("get lock.......");
            lockWork.invoke();
        } catch (InterruptedException e) {
           log.error("get lock thread interrupted!",e);
        } catch (Exception e) {
            log.error("get lock thread exception!",e);
        } finally {
            if (lock != null) {
                lock.unlock();
            }
            log.info("releases lock.......");
        }
    }
}

